package com.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.service.ClusterService;
import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

@Service
public class ClusterServiceImpl implements ClusterService {

    /**
     * 传入一个URL解析出URL的协议，主机名，端口号，请求参数
     * @param url
     * @return 带有URL相关信息的json对象
     */
    @Override
    public String getJson(String url) {

        Gson gson = new Gson();
        String result = null;
        //获取http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //响应对象
        CloseableHttpResponse response = null;

        try {
            //真实的URL对象
            URL realUrl = new URL(url);
            //Get请求对象
            HttpGet httpCet = new HttpGet(url);
            httpCet.addHeader("Content-Type","text/html;charset=utf-8");
            //创建请求配置对象并设置参数
            RequestConfig requestConfig = RequestConfig.custom()
                    //响应超时时间
                    .setSocketTimeout(20000)
                    //连接超时时间
                    .setConnectTimeout(20000)
                    .build();
            httpCet.setConfig(requestConfig);
            //执行get请求
            response = httpClient.execute(httpCet);


            if (200 == response.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = response.getEntity();

                //如果响应实体类不为空
                if (null != httpEntity) {
                    System.out.println(httpEntity.getContentEncoding());
//                    // result = gson.toJson(httpEntity);
                }
            } else {
                result = "请求失败:" + response.getStatusLine().getStatusCode();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("请求超时");
        }
        return result;
    }

    /**
     *
     * @param url
     * @return
     */
    public JSONObject showJsonByGet(String url) {

        JSONObject res = null;
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        //建立连接
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            if (200 == conn.getResponseCode()) {
                //获取服务器的相关信息
                is = conn.getInputStream();
                isr = new InputStreamReader(is,"UTF-8");
                br = new BufferedReader(isr);
                String line = null;
                StringBuffer sb = new StringBuffer();
                while (null != (line = br.readLine())) {
                    sb.append(line);
                }
                res = JSONObject.parseObject(sb.toString());
                System.out.println(res);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeStream(is, isr, br);
        }
        return res;

    }

    /**
     * 关闭流
     */
    public void closeStream(InputStream is, InputStreamReader isr, BufferedReader br) {

        if (null != br) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != isr) {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
